package com.qinggeng.framework.web.exception;

import com.alibaba.fastjson.JSONObject;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.exception.user.UserPasswordNotMatchException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import com.qinggeng.common.constant.HttpStatus;
import com.qinggeng.common.exception.BaseException;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.exception.DemoModeException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.web.domain.AjaxResult;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 全局异常处理器
 *
 * @author qinggeng
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler
{

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxSize;

    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public AjaxResult baseException(BaseException e)
    {
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public AjaxResult customException(CustomException customException)
    {
        return AjaxResult.error(customException.getCode(),customException.getMessage(),customException.getType());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public AjaxResult handlerNoFoundException(Exception e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(HttpStatus.NOT_FOUND, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAuthorizationException(AccessDeniedException e)
    {
        log.error(e.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
    }

    @ExceptionHandler(AccountExpiredException.class)
    public AjaxResult handleAccountExpiredException(AccountExpiredException e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public AjaxResult handleUsernameNotFoundException(UsernameNotFoundException e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(UserPasswordNotMatchException.class)
    public AjaxResult handleUserUserPasswordNotMatchException(UserPasswordNotMatchException e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    /**
     * MaxUploadSizeExceededException异常的特殊之处在于，当上传文件的大小超过限制时，它的抛出并是在进入Controller之前，
     * 所以不能在controller中利用注解@ExceptionHandler（MaxUploadSizeExceededException.class）来定义该异常的处理方法；
     * @param e
     * @param
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public AjaxResult multipartException(MaxUploadSizeExceededException e){
        log.error("文件上传超出大小"+e.getMaxUploadSize());
        //给前台显示
        throw new CustomException(500,"文件上传大小超限，最大"+maxSize+"MB。",ShowTypeEnum.用户.getValue());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult validatedBindException(BindException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public AjaxResult demoModeException(DemoModeException e)
    {
        return AjaxResult.error("演示模式，不允许操作");
    }
}
